import { useUserStore } from '@/store/user'
import { useMenuStore } from '@/store/menu'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus';
var router = null;
export async function beforeEach(to, from, next) {
    router = useRouter();
    document.title = to.meta.title ? to.meta.title : ''
    if (localStorage.getItem('TOKEN')) {
        if (to.path == '/login') {
            next('/')
        } else {
            try {
                const userStore = useUserStore();
                await userStore.getUserInfo()
                const menuStore = useMenuStore()
                initRouter(menuStore.menuList)
                if (to.matched.length == 0) {
                    router.push(to.fullPath);
                }

                if (userStore.permissions[0] == '*:*:*') {
                    next()
                } else if (!menuStore.mapMenuList.has(to.path)) {
                    ElMessage.error('没有此权限')
                    next('/')
                } else {
                    next()
                }
            } catch (err) {
                next('/login')
            }
        }
    } else {
        if (to.path == '/login') {
            next()
        } else {
            next('/login')
        }
    }
}

//加载动态路由和静态路由
const initRouter = (menuList) => {
    const newMenus = menuList || [];
    let menu = [...newMenus];
    //进行数据的重构
    let menuRouter = filterAsyncRouter(menu);
    // menuRouter = flatAsyncRoutes(menuRouter);
    menuRouter.forEach(item => {
        if (item.path != 'http://www.xuexiluxian.cn') {
            router.addRoute(item.parentView == 'layout' ? 'layout' : '', item);
        }
    })
}

//扁平化数据格式
function flatAsyncRoutes(routes, breadcrumb = []) {
    let res = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (tmp.children) {
            let childrenBreadcrumb = [...breadcrumb]
            childrenBreadcrumb.push(route)
            let tmpRoute = { ...route };
            tmpRoute.meta.breadcrumb = [...childrenBreadcrumb];
            delete tmpRoute.children;
            res.push(tmpRoute);
            let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb)
            childrenRoutes.map(item => {
                res.push(item)
            })
        } else {
            let tmpBreadcrumb = [...breadcrumb];
            tmpBreadcrumb.push(tmp)
            tmp.meta.breadcrumb = tmpBreadcrumb
            res.push(tmp)
        }
    })
    return res;
}

//转换格式
const filterAsyncRouter = (routerMap) => {
    const accessedRouters = [];
    routerMap.forEach(item => {
        let route = {
            parentView: item.parentView,
            path: item.path,
            name: item.name,
            meta: item.meta,
            children: item.children ? filterAsyncRouter(item.children) : null,
            component: loadComponent(item.component),
        }
        accessedRouters.push(route);
    })
    return accessedRouters;
}

//组件基本路径
const modules = import.meta.glob('@/views/**/*.vue');
const modulesMap = {};
Object.keys(modules).forEach(key => {
    const componentName = key.replace('/src/views', '').replace('.vue', '').replace('/index', '').replace('/', '');
    if (key.includes('index')) {
        modulesMap[`${componentName}/index`] = modules[key];
    }
    modulesMap[componentName] = modules[key];
})

//针对于路由组件的路径进行的调整 
const loadComponent = (component) => {
    if (component) {
        return modulesMap[component]
    }
}

export function afterEach(to, from, next) {


}